function fsb_realign_spm2(file_names,rea_par)

% FSB - SPM:  realign multiple subjects/sessions in y-direction first and
% subsequently realign mean subject/session images over all directions
% Uses SPM2 for realignment
% Looks for the first underscore of the subject file name to determine the
% length of the name prefix string which it subsequently uses to decide
% which subject/session a volume belongs to
%
% EXAMPLE:
% fsb_realign_multiple(file_names,rea_par)
%
% INPUT
% A list of file names (file_names)
% A parameter struct rea_par with the fields
% rea_par.rp
% rea_par.srt


%
% rea_par.rp == 0:  Simple realigment
%                   Images are realigned in y-direction only, then a mean
%                   image is written for each session/run/trial without
%                   reslicing the other images first, so the mean images
%                   are not yet corrected for y-shifts.
%
%
% rea_par.rp > 0 :  Complex realignment
%                   Images are realigned in y-direction only, then a SPM
%                   Realignment is done and the spatial transformation
%                   combined. Mean images are therefore corrected for
%                   y-shifts.
%
% rea_par.rp == 1 : 2-step realignment and reslicing
%                   Mean images are realigned, the parameters for the
%                   y-direction realignment and the mean image realignment
%                   are combined on a volume-by volume basis and
%                   a mat file is saved for every volume separately
%                   Images are then resliced and written such that they can
%                   be loaded into fMRI Sandbox again
%
% rea_par.rp == 3 : 2-step realignment and normalization
%                   Mean images are realigned, the parameters for the
%                   y-direction realignment are stored, and then the mean
%                   images are normalized to the first mean image as a
%                   template. The normalization parameters are saved and
%                   applied to all the volumes individually different.
%                   All images are normalized and written such that they
%                   can be loaded into fMRI Sandbox again.
%
% rea_par.rp == 4 : 2-step realignment and unwarping (not functional yet)
%                   Mean images are realigned, the parameters for the
%                   y-direction realignment and the mean image realignment
%                   are combined on a volume-by volume basis and
%                   a mat file is saved for every volume separately
%                   Images are then unwarped and written such that they
%                   can be loaded into fMRI Sandbox again.
%
% rea_par.srt:      Determines which column of the sandbox.intrial file is
%                   used for choosing the granularity of the realignment
%                   steps (e.g. trial-by-trial vs. session-by-session)
% Can use:
% A weighting image to determine which parts of the image should be used to
% determine the transformations.
%
% OUTPUT:
% Realigned images
% NOTES:
%
% External files:
% spm2_realign.m : Does the actual realignment in SPM2, just renamed
% fsb_load_files.m : Simple file loading function
% fsb_realing_yonly:
%
%
%$ Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if nargin<2
    rea_par.rp = 3;
    rea_par.srt = 4;
end

if nargin<3
    goutp =0;
end

set_spm2_path;
%set_spm5_path;
rehash;
global defaults
warning off; % Suppress warning about flipped image orientation

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Get files
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if ~exist('file_names','var');
    file_names = spm_get;
end

filnum = size(file_names,1);
file_names = cellstr(file_names);
file_names = file_names';
waitstr = ['Loading ' num2str(filnum) ' files'];
namecount = 1;
[pathstr, name{1}, ext, versn] = fileparts(file_names{1});
namepos = strfind(name,'_'); % Look for occurrences of underscores
namepos = namepos{1}; % Determine last letter of name prefix

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Determine file names
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

file_names_2{namecount}.name = name{1}(1:namepos); % Take the first namepos
%letters of the file name to determine to which dataset it belongs
file_names_2{namecount}.rname = ['r' name{1}(1:namepos) '.mat'];
file_names_2{namecount}.ons = 1;
file_names_2{namecount}.pathstr = pathstr;
thedir = file_names_2{1}.pathstr;
thedir = [thedir '\'];

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Sort file prefixes
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

h = waitbar(0,waitstr);
for x = 1:filnum
    waitbar(x/filnum)
    [pathstr, name{x}, ext, versn] = fileparts(file_names{x});
    if x>1 & strcmp(name{x}(1:namepos),name{x-1}(1:namepos)) ==  0;
        namecount = namecount+1;
        file_names_2{namecount}.name = name{x}(1:namepos);
        file_names_2{namecount}.rname = ['r' name{x}(1:namepos) '.mat'];
        file_names_2{namecount}.ons = x;
        file_names_2{namecount}.pathstr = pathstr;
    end
end

close (h);

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Run Realignment and Reslice and get image names
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

all_files = dir([thedir 't*.img']);
all_files = vertcat(all_files(:).name);
all_files = [all_files repmat(',1',size(all_files,1),1)];
f = [repmat(thedir,size(all_files,1),1) all_files];

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Get weighting images
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

wimagename = [thedir 'wimage.img'];
wtest{1} = wimagename;

try
    f_load_files(wtest);
catch
    disp('no weighting image present, using standard procedures')
    wimagename = '';
end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Run Realignment of images in all directions
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

G = spm_figure('GetWin','Graphics');
F = spm_figure('GetWin','Interactive');
fg = spm_figure('FindWin','Interactive');
spm_progress_bar('init');

realign_flags = struct('quality',1,...
    'fwhm',2,...
    'sep',2,...
    'interp',2,...
    'wrap',[0 0 0],...
    'rtm',0,...
    'PW',wimagename,...
    'graphics',1); % set flags for realignment

% Determine realignment parameters and write mat files
P_rea = spm_realign(f,realign_flags);

spm_progress_bar('clear');
warning off;
disp('done with image coregistration');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Prepare for reslicing or normalization
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P = {};

all_files = dir([thedir 'r' '*.img']);

if isempty(all_files) % if resliced images have not been written
    all_files = dir([thedir 't*.img']);
end

all_files = vertcat(all_files(:).name);
all_files = [all_files repmat(',1',size(all_files,1),1)];
P = [repmat(thedir,size(all_files,1),1) all_files];


%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%  reslice all images
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
spm_progress_bar('clear');
spm_progress_bar('init');
reslice_flags = struct('interp',4,'mask',1,'mean',0,'which',2,'wrap',[0 0 0]'); % reslice images
spm_reslice(P_rea,reslice_flags);
spm_progress_bar('clear');

close(fg);
close(G);

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%  save realignment information
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for x=1:size(P_rea,1)
    FSB_rea(:,:,x) = P_rea(x,1).mat;
end
save SPM_reapar.mat P_rea FSB_rea;

disp('Realignment : Done');
end

